package org.my.stock.util;

import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.internal.IgnitionEx;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MyDongFangType {
    private static String url_today = "https://push2.eastmoney.com/api/qt/clist/get?cb=jQuery1123037251977895899047_1744221129335&fid=f62&po=1&pz=50&pn=1&np=1&fltt=2&invt=2&ut=8dec03ba335b81bf4ebdf7b29ec27d15&fs=m%3A90+t%3A2&fields=f12%2Cf14%2Cf2%2Cf3%2Cf62%2Cf184%2Cf66%2Cf69%2Cf72%2Cf75%2Cf78%2Cf81%2Cf84%2Cf87%2Cf204%2Cf205%2Cf124%2Cf1%2Cf13";
    private static String url_5 = "https://push2.eastmoney.com/api/qt/clist/get?cb=jQuery1123037251977895899047_1744221129335&fid=f164&po=1&pz=50&pn=1&np=1&fltt=2&invt=2&ut=8dec03ba335b81bf4ebdf7b29ec27d15&fs=m%3A90+t%3A2&fields=f12%2Cf14%2Cf2%2Cf109%2Cf164%2Cf165%2Cf166%2Cf167%2Cf168%2Cf169%2Cf170%2Cf171%2Cf172%2Cf173%2Cf257%2Cf258%2Cf124%2Cf1%2Cf13";
    private static String url_10 = "https://push2.eastmoney.com/api/qt/clist/get?cb=jQuery1123016652517608918815_1744289250425&fid=f174&po=1&pz=50&pn=1&np=1&fltt=2&invt=2&ut=8dec03ba335b81bf4ebdf7b29ec27d15&fs=m%3A90+t%3A2&fields=f12%2Cf14%2Cf2%2Cf160%2Cf174%2Cf175%2Cf176%2Cf177%2Cf178%2Cf179%2Cf180%2Cf181%2Cf182%2Cf183%2Cf260%2Cf261%2Cf124%2Cf1%2Cf13";

    public static void updateAll_date() throws SQLException, InterruptedException, IgniteCheckedException {
        String springCfgPath = "/Users/chenfei/Documents/Java/my_database/my-stock/src/main/resources/default-config.xml";
        Ignite ignite = IgnitionEx.start(springCfgPath);
        CacheConfiguration<?, ?> cacheCfg = new CacheConfiguration<>("public_meta");
        cacheCfg.setSqlSchema("PUBLIC");

        IgniteCache<?, ?> cache = ignite.getOrCreateCache(cacheCfg);

        // 1. 获取当前日期（不含时间）
        LocalDate today = LocalDate.now();

        // 2. 转换为当天的午夜时间（默认时区）
        java.util.Date dateOnly = Date.from(
                today.atStartOfDay(ZoneId.systemDefault()).toInstant()
        );
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String day = sdf.format(dateOnly);

        //getData(ignite, cache, day, 1);
        getData(ignite, cache, day, 2);
    }

    public static void getData(Ignite ignite, IgniteCache<?, ?> cache, String day, int index) {
        String url = "https://push2.eastmoney.com/api/qt/clist/get?cb=jQuery1123037251977895899047_1744221129335&fid=f62&po=1&pz=50&pn="+ index +"&np=1&fltt=2&invt=2&ut=8dec03ba335b81bf4ebdf7b29ec27d15&fs=m%3A90+t%3A2&fields=f12%2Cf14%2Cf2%2Cf3%2Cf62%2Cf184%2Cf66%2Cf69%2Cf72%2Cf75%2Cf78%2Cf81%2Cf84%2Cf87%2Cf204%2Cf205%2Cf124%2Cf1%2Cf13";
        HttpClient httpClient = BrotliHttpClientHelper.createBrotliClient();

        try {
            // 1. 创建 GET 请求
            HttpGet request = new HttpGet(url);

            // 2. 设置请求头（防止被服务器拒绝）
            request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36");
            request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
            request.setHeader("Accept-Encoding", "gzip, deflate, br");
            request.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
            request.setHeader("Cache-Control", "max-age=0");
            request.setHeader("Connection", "keep-alive");
            request.setHeader("Cookie", "em_hq_fls=js; intellpositionL=1140px; em-quote-version=topspeed; intellpositionT=1298px; qgqp_b_id=e04e31a1e6446068e54e0f7808401919; sid=142772185; mtp=1; ct=oFv-pht6ZiYeFSXV2tPdRfkJ0x6ZftJa4X2TKji2eXO0Pl_YBbWxGBEwUTJ4z6N0GPPyYYrAizsB50OwF5PQc3x4HESZOAriGonI9ewh-RikgY0SEGHZcdA5RKg5RB4dPVIr3TCQLKkZkYOXQKFQElZVysNazqJ5O7csdsQO8U8; ut=FobyicMgeV5FJnFT189SwH2JOfiEw7mPz0LG7-oku6sFYOCxdbsEi2cnDTMMTwLC08VTgq_y28iF-S7gffFe0HKuLD1gS302VWRzT3pl7pFn5lPVWP0FGEkMzX3xkH4zZ26gwPXYW-E0EBZ8yNwMjA61nTdT3wPUm2MO4K_-pv5FU7C4OKwrxdk0UuppgrEnJEgArYW9ONwiZM25_K7mvoROgdu_rvCGeunwxnPYxpGqdl5zugvVg1iYtj7NhgcPysSINh74Fg1SOz2r1EMofNQ2h17qfzYUEa1h5_9kJkiB1FoE_P6A7kqYkMsr92-xF4fQoC_luUS273FRQNpqdmsbdOgZn9GV; pi=5274385825271944%3Bc5274385825271944%3B%E6%97%A0%E9%87%8F%E7%AB%A5%E5%AD%90%3BdCmpCdx6Fv0K9ySmGo1L60bQl9guPYNF9kW50ggeyA%2BOOeqCGeepIZPP0w088pbSCmH3QEBcYqyucZR9kKKJ4yNWHFBnnJznMgN%2F0PAMxp8Q%2FuJWZ89w97SHWrysOsb%2B93O45rM%2BhQroFhMO0X604MpHaHC%2F9yVsQmkbCVr5W1pviVaJGTOj%2FDWWzVmDAqUqGJzUNqW2%3BYeT6DxMds0uwdT3PftF0xut%2B1faguRkAY5Rpcphp0hhNyyGaYsTQbiMZEJxNWp7SrYuMigne0BGrZhWVS5SuyPZkN9SQHEd8yzBJUAbFcxV2So8rHP9l%2FY1Cf50pniZsBXw%2Bk0GvzjRxxPfbt9j1Vj8dTOWabw%3D%3D; vtpst=%7C; uidal=5274385825271944%E6%97%A0%E9%87%8F%E7%AB%A5%E5%AD%90; emshistory=%5B%22undefined%22%2C%22%E6%BD%9E%E5%AE%89%E7%8E%AF%E8%83%BD%22%5D; fullscreengg=1; fullscreengg2=1; st_si=82063303678764; st_asi=delete; HAList=ty-90-BK1139-%u4E2D%u7279%u4F30%2Cty-90-BK0712-%u4E00%u5E26%u4E00%u8DEF%2Cty-90-BK0479-%u94A2%u94C1%u884C%u4E1A%2Cty-90-BK0597-%u6C34%u5229%u5EFA%u8BBE%2Cty-0-002717-%u5CAD%u5357%u80A1%u4EFD%2Cty-1-603995-%u752C%u91D1%u80A1%u4EFD%2Cty-1-600188-%u5156%u77FF%u80FD%u6E90%2Cty-1-601699-%u6F5E%u5B89%u73AF%u80FD%2Cty-0-002128-%u7535%u6295%u80FD%u6E90%2Cty-0-001872-%u62DB%u5546%u6E2F%u53E3; st_pvi=18633756697256; st_sp=2021-05-13%2015%3A20%3A17; st_inirUrl=https%3A%2F%2Fcn.bing.com%2F; st_sn=54; st_psi=20250411000412279-113200301353-4184025997");
            request.setHeader("Host", "push2.eastmoney.com");

            // 3. 执行请求并获取响应
            HttpResponse response = httpClient.execute(request);

            // 4. 检查状态码
            //int statusCode = response.getStatusLine().getStatusCode();
            //System.out.println("所属类型: " + type);

            // 5. 读取响应内容
            HttpEntity entity = response.getEntity();
            if (entity != null) {

                // 关键：使用 UTF-8 编码转换解压后的字节流
                String content = EntityUtils.toString(entity, "UTF-8");
                toDb(ignite, cache, content, day);
                System.out.println("解码内容:\n" + content);
            }

        } catch (Exception e) {
            System.err.println("请求失败: " + e.getMessage());
        } finally {
            // 6. 释放连接（重要！）
            httpClient.getConnectionManager().shutdown();
        }
    }

    public static void toDb(Ignite ignite, IgniteCache<?, ?> cache, final String line, String day) throws SQLException {
        Pattern pattern = Pattern.compile("\\(([^)]+)\\)");
        Matcher matcher = pattern.matcher(line);

        if (matcher.find()) {
            String result = matcher.group(1); // 获取第一个捕获组内容

            LinkedTreeMap m = MyUtil.getGson().fromJson(result, new TypeToken<LinkedTreeMap>() {
            }.getType());
            LinkedTreeMap data = (LinkedTreeMap) m.get("data");
            List<LinkedTreeMap> diff = (List<LinkedTreeMap>) data.get("diff");
            try {

                for (LinkedTreeMap tm : diff) {
                    // 涨跌
                    double f3 = (double) tm.get("f3");
                    // 股票编号
                    String f12 = (String) tm.get("f12");
                    // 主流净流入
                    double f62 = (double) tm.get("f62");
                    //String f62 = (String) tm.get("f62");
                    // 主流净占比
                    double f184 = (double) tm.get("f184");
                    // 股票名字
                    String f14 = (String) tm.get("f14");

                    long id = ignite.atomicSequence("public_meta", 0, true).incrementAndGet();
                    String sql = "insert into public.stock_type_date (id, symbol, main_fund, main_fund_bf, name, zhangdie, stock_date) values ("+ id +", '" + f12 + "', " + f62 + ", " + f184 + ", '" + f14 + "', " + f3 + ", '" + day + "')";
                    cache.query(new SqlFieldsQuery(sql)).getAll();
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }
}











































